package Synchronized;

/**
 * 不安全的买票
 * @author luyao_start
 * @create 2021-08-19-20:50
 */
public class UnsafeBuyTicket {
    public static void main(String[] args) {
        BuyTicket station = new BuyTicket();
        new Thread(station,"我").start();
        new Thread(station,"你").start();
        new Thread(station,"他").start();
    }
}

class BuyTicket implements Runnable{
    private int ticketnum = 500;
    boolean flag = true;

    @Override
    public void run() {
        while (flag){
            try {
                buy();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    //同步方法,锁的是this
    //用代码块的话，需要去锁变化的量
    private synchronized void buy(){
        if(ticketnum <= 0){
            flag = false;
            return;
        }
        System.out.println(Thread.currentThread().getName()+"拿到"+ticketnum--);

    }
}
